package com.chandon.juc.thread_communication.AlternatePrinting;

import java.util.concurrent.Semaphore;

/**
 * 2个线程交替打印A与B，重复n次
 *
 * @author Dong
 */

public class UseSemaphore {

	public static void main(String[] args) {
		test();
	}

	static Semaphore semaphoreA = new Semaphore(1);
	static Semaphore semaphoreB = new Semaphore(0);


	public static void test() {


		Thread threadA = new Thread(() -> {

			try {
				for (int i = 0; i < 50; i++) {

					semaphoreA.acquire();
					System.out.println("A:" + i);
					semaphoreB.release();
				}

			} catch (InterruptedException e) {
				throw new RuntimeException(e);
			}

		});


		Thread threadB = new Thread(() -> {

			try {
				for (int i = 0; i < 50; i++) {
					semaphoreB.acquire();
					System.out.println("B:" + i);
					semaphoreA.release();
				}
			} catch (Exception e) {
				throw new RuntimeException(e);
			}

		});
		threadB.start();
		threadA.start();

	}

}
